<?php

class PlatformFacebook extends PlatformBase
{
    /**
     * @var PlatformFacebook
     */
    private static $instance;

    /**
     * Get the instance of PlatformFacebook.
     *
     * @return PlatformFacebook
     */
    public static function get()
    {
        if (!self::$instance) {
            self::$instance = new PlatformFacebook();
        }
        return self::$instance;
    }

    private function __construct()
    {
        $this->configs = SzConfig::get()->loadAppConfig(ModuleSns::getSnsConfigFileName(self::PLATFORM_FACEBOOK), null, true);

        $this->appId = $this->configs['appId']['value'];
        //$this->requestUrl = $this->configs['requestUrl']['value'];
        $this->appSecret = $this->configs['appSecret']['value'];
    }

    protected function base64UrlDecode($input)
    {
        return base64_decode(strtr($input, '-_', '+/'));
    }

    /**
     * 验证token
     *
     * @param string $platformId 平台ID
     * @param string $token 登录token
     * @return bool
     */
    public function checkToken($platformId, $token)
    {
        list($encodedSig, $payload) = explode('.', $token, 2);

        // decode the data
        $sig = $this->base64UrlDecode($encodedSig);
        $data = json_decode($this->base64UrlDecode($payload), true);

        if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
            return false;
        }

        $expectedSig = hash_hmac('sha256', $payload, $this->appSecret, true);
        if ($sig != $expectedSig) {
            return false;
        }
        return true;
    }
}